<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>just view</title>
<script type="text/javascript" src="o3djs/base.js">
</script>
<script type="text/javascript">
o3djs.require('o3djs.util');
o3djs.require('o3djs.math');
o3djs.require('o3djs.rendergraph');
o3djs.require('o3djs.material');
o3djs.require('o3djs.pack');
o3djs.require('o3djs.loader');
o3djs.require('o3djs.primitives');
var PI = Math.PI;
//-----------------------------------------------------------------全局对象
var o3dElement;
var cubeClient;
var cubeO3d;
var cubePack;
var o3dMath;
//
var viewInfo;
var backViewInfo;
//
var cubeMass = new Array;
var backImage = new Array;//背景大对象
var shape = new Array;//存储shape的原始体
//--------------------------------------------------------------------视觉投影对象
var eyeMoveDelta = new Array;//视角角度增量值的缓存
var eyeOri = [3*PI/4,PI/4,40,0,0,0];
var eyePosi = new Array;
var eyeAngle = new Array;
var eyeR;
var viewCenter = new Array;
var eyeTarAmong;
//--------------------------------------------------------------------有关互动操作的变量
var zoomFactor = 1.7;
var moveFactor = 0.005;
var moveTime;//通用的动作时间函数
var mouseButton = new Array;//全局的开关
var cubeDragging = false;
//---------------------------------------------------------------------------------
var cubeFinished = false;
var cubeSelect = new Array ;
var backMaterial;
var zBuffer = 3000;//Z值缓冲，使用后应自加1,最高是4000
var materialUrls = [
	'ishader/texture-colormult.shader'
	];
var textures = new Array;
var textureUrls = [
					"ipic/menu_blank.png",
					];

window.onload = init;
window.onunload = uninit;

function init(){
	o3djs.util.makeClients(initCreateCube);
	}
	
function uninit() {
    if (cubeClient) {
   		cubeClient.cleanup();
  		}
	}

function initCreateCube(clientElements){
	o3dElement = clientElements[0];
	cubeClient = o3dElement.client;
	cubeO3d = o3dElement.o3d;
	o3dMath = o3djs.math;
	cubePack = cubeClient.createPack(); 
	
	cubeMass.transform = cubePack.createObject("Transform");
	cubeMass.transform.parent = cubeClient.root;
	//给每个MAss 都具有一个本地的x,y,z;加快执行maaa操作的执行
	cubeMass.x = 0;
	cubeMass.y = 0;
	cubeMass.z = 0;
	cubeMass.localX = 0;
	cubeMass.localY = 0;
	cubeMass.localZ = 0;
	cubeSelect.push(cubeMass);
	
	backImage.transform = cubePack.createObject("Transform");
	backImage.transform.parent = cubeClient.root;

	initEye();
	initViewInfo();	
	initTexture();//进入一个加载贴图的等待函数。
	shape[0] = new creator.oriCube();
	}
	
function initTexture(){
	var loader = o3djs.loader.createLoader(afterTextureLoaded);
	var textureLinkName;
	for(var n=0;n<textureUrls.length;n++){
		textureLinkName = textureUrls[n];
		textureLinkName = cutUrlToSingle(textureLinkName);
		textures[textureLinkName] = textureUrls[n];
		loadTexture(loader,textureLinkName);
		}
	loader.finish();
	}

function loadTexture(loader,urlObj){
	loader.loadTexture(cubePack, textures[urlObj], function(texture, exception) {
					   if (exception) {
					   alert(exception);
					   }
					   else {
					   textures[urlObj] = texture;}});
	}
	
//图像加载完成后进行的事情，有关图像贴图的都应该写在这里面---------------------------------
function afterTextureLoaded(){
	//初始化背景----------------------------------------------------------
	backGround.init();
	//创建第一个方块
	initEvent();
	cubeFinished = true;
	}
	
function cutUrlToSingle(url){
	var subNum = url.indexOf("/");
	var subUrl = url.slice(subNum + 1);
	subNum = subUrl.indexOf("/");
	if(subNum == -1){
		subNum = subUrl.indexOf(".");
		subUrl = subUrl.slice(0,subNum);
		return  subUrl;
		}
		else{
			return cutUrlToSingle(subUrl);
			}
	
	}	

function initEye(){
	eyeAngle[0] = eyeOri[0];
	eyeAngle[1] = eyeOri[1];
	eyeR = eyeOri[2];
	viewCenter[0] = eyeOri[3];
	viewCenter[1] = eyeOri[4];
	viewCenter[2] = eyeOri[5];
	eyePosi[2] = eyeR*Math.cos(eyeAngle[1])*Math.sin(eyeAngle[0]) + viewCenter[2];
	eyePosi[1] = eyeR*Math.sin(eyeAngle[1]) + viewCenter[1];
	eyePosi[0] = eyeR*Math.cos(eyeAngle[1])*Math.cos(eyeAngle[0]) + viewCenter[0];
	}
	
function initViewInfo(){
	viewInfo = o3djs.rendergraph.createBasicView(cubePack,
												 cubeMass.transform,
												 cubeClient.renderGraphRoot);
	viewInfo.drawContext.projection = o3dMath.matrix4.perspective(o3dMath.degToRad(30),
																	  cubeClient.width/cubeClient.height,
																	  1,
																	  2000);
	viewInfo.drawContext.view = o3dMath.matrix4.lookAt(eyePosi,
														viewCenter,
														[0,1,0]);
	//viewInfo.clearBuffer.clearColor = [1,1,1,0]
	viewInfo.clearBuffer.clearColorFlag = false;
	//操作背景的视图对象
	backViewInfo = o3djs.rendergraph.createBasicView(cubePack,
													 backImage.transform,
													 cubeClient.renderGraphRoot);
	backViewInfo.drawContext.projection = o3dMath.matrix4.orthographic(0.5,
																	   cubeClient.width + 0.5,
																	   cubeClient.height + 0.5,
																	   0.5,
																	   100,
																	   1000);
	backViewInfo.drawContext.view = o3dMath.matrix4.lookAt( [0, 0, 1],
															[0, 0, 0],
															[0, 1, 0]);
	
	backViewInfo.root.priority = viewInfo.root.priority - 1;
	backViewInfo.clearBuffer.clearColorFlag = false;
	backViewInfo.zOrderedState.getStateParam("CullMode").value = cubeO3d.State.CULL_NONE;
	backViewInfo.zOrderedState.getStateParam("ZWriteEnable").value = false;
	}

function initEvent(){
	o3djs.event.addEventListener(o3dElement,"mousedown",listen.startDragging);
	o3djs.event.addEventListener(o3dElement,"mousemove",listen.drag);
	o3djs.event.addEventListener(o3dElement,"mouseup",listen.stopDragging);
	o3djs.event.addEventListener(o3dElement,"wheel",listen.scrollCubes);
	o3djs.event.addEventListener(o3dElement,'keydown',listen.keyDown);
	o3djs.event.addEventListener(o3dElement,'dblclick',listen.editMass);
	}
	
	
//一系列附加函数----------------------------------------------------------------------
var listen = listen || {};

listen.startDragging = function(E){
	eyeMoveDelta[0] = eyeMoveDelta[2] = E.x;
	eyeMoveDelta[1] = eyeMoveDelta[3] = E.y;	
	eyeMoveDelta[4] = eyeMoveDelta[10] = eyeAngle[0];
	eyeMoveDelta[5] = eyeMoveDelta[11] = eyeAngle[1];
	eyeMoveDelta[6] = eyeR;
	eyeMoveDelta[7] = viewCenter[0];
	eyeMoveDelta[8] = viewCenter[1];
	eyeMoveDelta[9] = viewCenter[2];
	cubeClient.cursor = cubeO3d.Cursor.DEFAULT;
	
	if(E.button == 0){
		mouseButton["leftButton"] = true;
		}
	else if (E.button == 1){
		mouseButton["move"] = true;
		}
	else if (E.button == 2){
		mouseButton["rotation"] = true;
		}
	cubeDragging = true;
	}

listen.drag = function(E){
		eyeMoveDelta[2] = E.x;
		eyeMoveDelta[3] = E.y;
		cubeClient.cursor = cubeO3d.Cursor.DEFAULT;
			if (mouseButton["move"]){
				eyeTarAmong = null;
				var rY = (eyeMoveDelta[3] - eyeMoveDelta[1]) * moveFactor * eyeMoveDelta[6] * 0.1;
				var aY = eyeMoveDelta[4] - PI;
				var bY = PI/2 - eyeMoveDelta[5];
				var rX = (eyeMoveDelta[0] - eyeMoveDelta[2]) * moveFactor * eyeMoveDelta[6] * 0.1;
				var aX = eyeMoveDelta[4] - PI/2;
				var targetZ = rY*Math.cos(bY)*Math.sin(aY) + rX*Math.sin(aX) + eyeMoveDelta[9];
				var targetY = rY*Math.sin(bY) + eyeMoveDelta[8];
				var targetX = rY*Math.cos(bY)*Math.cos(aY) + rX*Math.cos(aX) + eyeMoveDelta[7];
				view.moveViewCenter([targetX,targetY,targetZ]);
				}
				else if (mouseButton["rotation"]){
					eyeTarAmong = null;
					var angleAfter = new Array;
					angleAfter[0]  = (eyeMoveDelta[2]-eyeMoveDelta[0]) * moveFactor + eyeMoveDelta[4];
					var angleTest =  (eyeMoveDelta[3]-eyeMoveDelta[1]) * moveFactor + eyeMoveDelta[5];
					if (angleTest >= 0){
						angleAfter[1] = Math.abs(angleTest)>PI/2 - 0.001 ? PI/2 - 0.001: angleTest;
						}
						else{
							angleAfter[1] = Math.abs(angleTest)>PI/2 - 0.001 ? -PI/2 + 0.001: angleTest;
							}
					view.angleRotate(angleAfter);
					}
	}

listen.stopDragging = function(E){
		eyeAngle[0] = view.PiRound(eyeAngle[0]);
		eyeAngle[1] = view.PiRound(eyeAngle[1]);
		cubeDragging = false;
		cubeClient.cursor = cubeO3d.Cursor.DEFAULT;
		
		mouseButton["leftButton"] = false;//代表左键按下的开关，listen.drag函数中使用。因为drag的触发取不到左右键
		mouseButton["zoom"] = false;
		mouseButton["move"] = false;
		mouseButton["rotation"] = false;
		mouseButton["drawSelect"] = false;
		mouseButton["directMove"] = false;
		mouseButton["picking"] = false;
		mouseButton["zoomfalse"] = false;
	}

listen.scrollCubes = function(E){
	if(!mouseButton["zoomfalse"]){
			mouseButton["zoomfalse"] = true;
			var zoom = (E.deltaY>0) ? 1/zoomFactor : zoomFactor;
			view.zoomEyeR(eyeR*zoom,15);
			eyeTarAmong = null;
		}
	}


listen.keyDown = function(E){//应该给相应的开关，否则会出错
			switch(E.keyCode){
				case 32: //空格
					view.resetView();
					break;
				case 79://o
					var createString = document.getElementById("createString").value;
					worker.create(createString);
					break;
				case 38:
					menuFunction.menuReviewUp();
					break;
				case 37:
					menuFunction.menuReviewLeft();
					break;
				case 40:
					menuFunction.menuReviewDown();
					break;
				case 39:
					menuFunction.menuReviewRight();
					break;
				case 46://del
					worker.removeCubes();
					break;
				}
			

	}


listen.editMass = function(E){

					view.resetView();
	}

var menuFunction = menuFunction || {};

menuFunction.menuReviewUp = function(){
	var eyeAfter = [PI/2,PI/2-0.001,eyeR,viewCenter[0],viewCenter[1],viewCenter[2]];
	view.changeView(eyeAfter,30);
	}
	
menuFunction.menuReviewDown = function(){
	var eyeAfter = [PI/2,0,eyeR,viewCenter[0],viewCenter[1],viewCenter[2]];
	view.changeView(eyeAfter,30);
	}	
	
menuFunction.menuReviewLeft = function(){
	var eyeAfter = [PI,0,eyeR,viewCenter[0],viewCenter[1],viewCenter[2]];
	view.changeView(eyeAfter,30);
	}
	
menuFunction.menuReviewRight = function(){
	var eyeAfter = [PI*3/4,PI/4,eyeR,viewCenter[0],viewCenter[1],viewCenter[2]];
	view.changeView(eyeAfter,30);
	}	




var view = view || {};//视角变换等一些的操作对象。
 

view.moveViewCenter = function(centerAfter,tStep){
	clearInterval(moveTime);
	if (!tStep){
		eyePosi[0] = eyePosi[0] + centerAfter[0] - viewCenter[0];
		viewCenter[0] = centerAfter[0];	
		eyePosi[1] = eyePosi[1] + centerAfter[1] - viewCenter[1];
		viewCenter[1] = centerAfter[1];
		eyePosi[2] = eyePosi[2] + centerAfter[2] - viewCenter[2];
		viewCenter[2] = centerAfter[2];
		viewInfo.drawContext.view = o3dMath.matrix4.lookAt(
															eyePosi,
															viewCenter,
															[0,1,0]
															 );
		worker.updataAllLight();
		moveTime = null;
		}
		else{
			var eyeBefore = [eyePosi[0],eyePosi[1],eyePosi[2],viewCenter[0],viewCenter[1],viewCenter[2]];
			var centerL = new Array;
			centerL[0] = centerAfter[0] - viewCenter[0];
			centerL[1] = centerAfter[1] - viewCenter[1];
			centerL[2] = centerAfter[2] - viewCenter[2];
			var n = 0;							
			moveTime = setInterval(function(){view._moveSmooth(eyeBefore,centerL,n,tStep);n++;},10);
			}
	}
	
view._moveSmooth = function(eyeBefore,centerL,n,tStep){
		eyePosi[0] = eyeBefore[0] + Math.sin(PI/2*n/tStep)*centerL[0];
		viewCenter[0] = eyeBefore[3] + Math.sin(PI/2*n/tStep)*centerL[0];	
		eyePosi[1] = eyeBefore[1] + Math.sin(PI/2*n/tStep)*centerL[1];
		viewCenter[1] = eyeBefore[4] + Math.sin(PI/2*n/tStep)*centerL[1];
		eyePosi[2] = eyeBefore[2] + Math.sin(PI/2*n/tStep)*centerL[2];
		viewCenter[2] = eyeBefore[5] + Math.sin(PI/2*n/tStep)*centerL[2];
							viewInfo.drawContext.view = o3dMath.matrix4.lookAt(
																			  eyePosi,
																			  viewCenter,
																			  [0,1,0]
																		  );
		worker.updataAllLight();
		if (n>=tStep){
		clearInterval(moveTime);
		moveTime = null;
		}
	}
	
view.PiRound = function(rad){
	if (rad>PI){
		rad -= 2*PI;
		}
		else if(rad<=-PI){
				rad += 2*PI;
			}
		return rad;
	}

view.angleRotate = function(angleAfter,tStep){
	clearInterval(moveTime);
	if (!tStep){
				eyeAngle = angleAfter;
				eyePosi[2] = eyeR*Math.cos(eyeAngle[1])*Math.sin(eyeAngle[0]) + viewCenter[2];
				eyePosi[1] = eyeR*Math.sin(eyeAngle[1]) + viewCenter[1];
				eyePosi[0] = eyeR*Math.cos(eyeAngle[1])*Math.cos(eyeAngle[0]) + viewCenter[0];
				viewInfo.drawContext.view = o3dMath.matrix4.lookAt(
																  eyePosi,
																  viewCenter,
																  [0,1,0]
																  );
		worker.updataAllLight();
		moveTime = null;
		}
		else{
			var angleBefore = eyeAngle;
			var angleL = new Array;
			angleL[0] = angleAfter[0] - angleBefore[0];
			angleL[1] = angleAfter[1] - angleBefore[1];
			var n = 0;
			moveTime = setInterval(function(){angleSmooth(angleBefore,angleL,n,tStep);n++;},10);
			}
	}
	
view.zoomEyeR = function(eyeRAfter,tStep){
	clearInterval(moveTime);
	if(!tStep){
		eyeR = eyeRAfter;
		eyeR = eyeR < 3 ? 3 : eyeR;
		eyePosi[2] = eyeR*Math.cos(eyeAngle[1])*Math.sin(eyeAngle[0]) + viewCenter[2];
		eyePosi[1] = eyeR*Math.sin(eyeAngle[1]) + viewCenter[1];
		eyePosi[0] = eyeR*Math.cos(eyeAngle[1])*Math.cos(eyeAngle[0]) + viewCenter[0];
		viewInfo.drawContext.view = o3dMath.matrix4.lookAt(
														  eyePosi,
														  viewCenter,
														  [0,1,0]
														  );
		worker.updataAllLight();
		moveTime = null;
		}
		else{
			var eyeRBefore = eyeR;
			var rL = eyeRAfter - eyeRBefore;
			var n = 0;
			moveTime = setInterval(function(){view._zoomSmooth(eyeRBefore,rL,n,tStep);n++;},10);
			}	
	}


view._zoomSmooth = function(eyeRBefore,rL,n,tStep) {
	eyeR = eyeRBefore + Math.sin(PI/2*n/tStep)*rL;
    eyeR = eyeR < 3 ? 3 : eyeR;
	eyePosi[2] = eyeR*Math.cos(eyeAngle[1])*Math.sin(eyeAngle[0]) + viewCenter[2];
	eyePosi[1] = eyeR*Math.sin(eyeAngle[1]) + viewCenter[1];
	eyePosi[0] = eyeR*Math.cos(eyeAngle[1])*Math.cos(eyeAngle[0]) + viewCenter[0];
    viewInfo.drawContext.view = o3dMath.matrix4.lookAt(
													  eyePosi,
													  viewCenter,
													  [0,1,0]
													  );
		worker.updataAllLight();
		if (n>=tStep){
		clearInterval(moveTime);
		mouseButton["zoomfalse"] = false;
		moveTime = null;
		}
	}

view.maxMinCoordinate = function(mass){
	var maxMinCoor = new Array;
	var returnMaxMin = new Array;
	
		for (var m=0;m<mass.length;m++){
			if (mass[m][0]){ 
							returnMaxMin = view.maxMinCoordinate(mass[m]);
							}
							else{returnMaxMin[0] = mass[m].x;
								  returnMaxMin[1] = mass[m].x;
								  returnMaxMin[2] = mass[m].y;
								  returnMaxMin[3] = mass[m].y;
								  returnMaxMin[4] = mass[m].z;
								  returnMaxMin[5] = mass[m].z;
								}
			maxMinCoor[0] = maxMinCoor[0] == undefined ? returnMaxMin[0] : Math.max(maxMinCoor[0],returnMaxMin[0]);
			maxMinCoor[1] = maxMinCoor[1] == undefined ? returnMaxMin[1] : Math.min(maxMinCoor[1],returnMaxMin[1]);
			maxMinCoor[2] = maxMinCoor[2] == undefined ? returnMaxMin[2] : Math.max(maxMinCoor[2],returnMaxMin[2]);
			maxMinCoor[3] = maxMinCoor[3] == undefined ? returnMaxMin[3] : Math.min(maxMinCoor[3],returnMaxMin[3]);
			maxMinCoor[4] = maxMinCoor[4] == undefined ? returnMaxMin[4] : Math.max(maxMinCoor[4],returnMaxMin[4]);
			maxMinCoor[5] = maxMinCoor[5] == undefined ? returnMaxMin[5] : Math.min(maxMinCoor[5],returnMaxMin[5]);
					}
	return maxMinCoor;
	}

view.resetView = function(){
	if (cubeSelect[cubeSelect.length-1][0]){
		if (!cubeDragging){
			var maxMinCoor = view.maxMinCoordinate(cubeSelect[cubeSelect.length-1]);
			var ax = maxMinCoor[0];
			var bx = maxMinCoor[1];
			var ay = maxMinCoor[2];
			var by = maxMinCoor[3];
			var az = maxMinCoor[4];
			var bz = maxMinCoor[5];	
			var targetR = Math.max( Math.max(Math.abs(ax-bx+1),Math.abs(ay-by+1)),Math.abs(az-bz+1))*2; 
			var targetX = (ax + bx)/2;
			var targetY = (ay + by)/2;
			var targetZ = (az + bz)/2;
			if (targetR<10){targetR = 10;}
			
			var eyeTar = [eyeAngle[0],eyeAngle[1],targetR,targetX,targetY,targetZ];
			if (!eyeTarAmong){
				eyeTarAmong = [eyeAngle[0],eyeAngle[1],eyeR,viewCenter[0],viewCenter[1],viewCenter[2]];
				view.changeView(eyeTar,30);
				}
			else{
				view.changeView(eyeTarAmong,30);
				eyeTarAmong = null;
				}
			}
	}
	}

	
view.changeView = function(eyeAfter,tStep){
		clearInterval(moveTime);
		var tStep = !tStep ? 50 : tStep;
		var eyeBefore = [eyeAngle[0],eyeAngle[1],eyeR,viewCenter[0],viewCenter[1],viewCenter[2]];
		var aL = eyeAfter[0] - eyeAngle[0];
		if (aL>PI){
			aL -= 2*PI;
			}
			else if(aL<-PI){
				aL += 2*PI;
				}
		var bL = eyeAfter[1] - eyeAngle[1];
		var rL = eyeAfter[2] - eyeR;
		var xL = eyeAfter[3] - viewCenter[0];
		var yL = eyeAfter[4] - viewCenter[1];
		var zL = eyeAfter[5] - viewCenter[2];
		var n = 0;
		moveTime = setInterval(function(){view._changeEye(eyeBefore,aL,bL,rL,xL,yL,zL,n,tStep);n++;},10);
	}


view._changeEye = function(eyeBefore,aL,bL,rL,xL,yL,zL,n,tStep){
	
	
	eyeAngle[0] = eyeBefore[0] + Math.sin(PI/2*n/tStep)*aL;
	eyeAngle[1] = eyeBefore[1] + Math.sin(PI/2*n/tStep)*bL;
	eyeR = eyeBefore[2] + Math.sin(PI/2*n/tStep)*rL;
	viewCenter[0] = eyeBefore[3] + Math.sin(PI/2*n/tStep)*xL;
	viewCenter[1] = eyeBefore[4] + Math.sin(PI/2*n/tStep)*yL;
	viewCenter[2] = eyeBefore[5] + Math.sin(PI/2*n/tStep)*zL;
	
	eyePosi[2] = eyeR*Math.cos(eyeAngle[1])*Math.sin(eyeAngle[0]) + viewCenter[2];
	eyePosi[1] = eyeR*Math.sin(eyeAngle[1]) + viewCenter[1];
	eyePosi[0] = eyeR*Math.cos(eyeAngle[1])*Math.cos(eyeAngle[0]) + viewCenter[0];
	
	viewInfo.drawContext.view = o3dMath.matrix4.lookAt(
													  eyePosi,
													  viewCenter,
													  [0,1,0]
													  );
		worker.updataAllLight();
	if (n>=tStep){
		clearInterval(moveTime);
		moveTime = null;
		}
	}
	
	
	
var creator = creator || {};//模型创建对象

creator.copyCube = function(cubeShape,colorRed,colorGreen,colorBlue,cubeAlpha,localX,localY,localZ,localL){
	
	var parent = cubeSelect[cubeSelect.length-1];
	var worldX = parent.x+localX;
	var worldY = parent.y+localY;
	var worldZ = parent.z+localZ;
	
		this.red = colorRed;
		this.green = colorGreen;
		this.blue = colorBlue;
		this.alpha = cubeAlpha;
		this.x = worldX;
		this.y = worldY;
		this.z = worldZ;
		this.l = localL
		this.localX = localX;
		this.localY = localY;
		this.localZ = localZ;
		this.parent = cubeSelect[cubeSelect.length-1];
		this.transform = cubePack.createObject("Transform");
		this.transform.parent = cubeSelect[cubeSelect.length-1].transform;
		this.transform.addShape(cubeShape);
		this.transform.translate(localX,
								 localY,
								 localZ);
		this.transform.scale(localL,
							 localL,
							 localL);
		this.transform.createParam("diffuse","ParamFloat4").value = [
																	 this.red,
																	 this.green,
																	 this.blue,
																	 this.alpha
																	 ];
	}
	
	
creator.oriCube = function(){
	this.cubeMaterial = cubePack.createObject("Material");
	this.cubeMaterial.drawList = viewInfo.zOrderedDrawList; 
	this.cubeMaterial.createParam("diffuse","ParamFloat4").value = [1,1,1,1];
	
	this.cubeMaterial.createParam('emissive', 'ParamFloat4').value = [0, 0, 0, 1]; 
	this.cubeMaterial.createParam('ambient', 'ParamFloat4').value = [0, 0, 0, 1];
	this.cubeMaterial.createParam('specular', 'ParamFloat4').value = [1, 1, 1, 1];
	this.cubeMaterial.createParam('shininess', 'ParamFloat').value = 100;
	this.cubeMaterial.createParam('specularFactor', 'ParamFloat').value = 0.25;
	
	this.cubeMaterial.createParam('lightColor', 'ParamFloat4').value = [1, 1, 1, 1]; 
	this.lightPositionParam = this.cubeMaterial.createParam('lightWorldPos', 'ParamFloat3'); 
	this.lightPositionParam.value = eyePosi;
	
	this.record = o3djs.effect.buildStandardShaderString(this.cubeMaterial,"phong"); 
	this.effect = cubePack.createObject("Effect");
	this.effect.name = this.record.description;
	this.effect.loadFromFXString(this.record.shader);
	this.cubeMaterial.effect = this.effect;
	this.effect.createUniformParameters(this.cubeMaterial); 

	var a = 1/2;
	this.positionArray = [	 -a, +a, +a,
 						     +a, +a, +a,
							 -a, -a, +a,
     						 +a, -a, +a,
 						     +a, +a, +a,
 						     +a, +a, -a,
 						     +a, -a, +a,
 						     +a, -a, -a,
 						     +a, +a, -a,
 						     -a, +a, -a,
 						     +a, -a, -a,
 						     -a, -a, -a,
 						     -a, +a, -a,
 						     -a, +a, +a,
 						     -a, -a, -a,
 						     -a, -a, +a,
 						     -a, +a, -a,
 						     +a, +a, -a,
 						     -a, +a, +a,
 						     +a, +a, +a,
 						     -a, -a, +a,
 						     +a, -a, +a,
 						     -a, -a, -a,
 						     +a, -a, -a
							 ];
	
	this.normalArray = [	    0, 0, 1,
								0, 0, 1,
								0, 0, 1,
								0, 0, 1,
								1, 0, 0,
								1, 0, 0,
								1, 0, 0,
								1, 0, 0,
								0, 0,-1,
								0, 0,-1,
								0, 0,-1,
								0, 0,-1,
							   -1, 0, 0,
							   -1, 0, 0,
							   -1, 0, 0,
							   -1, 0, 0,
							    0, 1, 0,
							    0, 1, 0,
							    0, 1, 0,
							    0, 1, 0,
							    0,-1, 0,
							    0,-1, 0,
							    0,-1, 0,
							    0,-1, 0
								];

	this.indicesArray = [	  0, 2, 1,
							  2, 3, 1,
							  4, 6, 5, 
							  6, 7, 5,
							  8, 10,9,
							  10,11,9,
							  12,14,13, 
							  14,15,13,
							  16,18,17, 
							  18,19,17, 
							  20,22,21, 
							  22,23,21
							  ];
	
	this.cubeShape = cubePack.createObject("Shape");
	this.cubePrimitive = cubePack.createObject("Primitive");
	this.streamBank = cubePack.createObject("StreamBank");
	
	this.cubePrimitive.material = this.cubeMaterial;
	this.cubePrimitive.owner = this.cubeShape;
	this.cubePrimitive.streamBank = this.streamBank;
	
	this.cubePrimitive.primitiveType = cubeO3d.Primitive.TRIANGLELIST;
	this.cubePrimitive.numberPrimitives = 12;
	this.cubePrimitive.numberVertices = 24;
	this.cubePrimitive.createDrawElement(cubePack,null);
	
	this.positionBuffer = cubePack.createObject("VertexBuffer");
	this.positionField = this.positionBuffer.createField("FloatField",3);
	this.streamBank.setVertexStream(
									cubeO3d.Stream.POSITION,
									0,
									this.positionField,
									0);
	this.normalField = this.positionBuffer.createField("FloatField",3);
	this.streamBank.setVertexStream(
									cubeO3d.Stream.NORMAL,
									0,
									this.normalField,
									0);
 
    this.positionBuffer.allocateElements(24); 	
	
	this.positionField.setAt(0,this.positionArray);
	this.normalField.setAt(0,this.normalArray);
	
	this.indexBuffer = cubePack.createObject("IndexBuffer");
	this.indexBuffer.set(this.indicesArray);
	this.cubePrimitive.indexBuffer = this.indexBuffer;
	}

creator.oriCube.prototype.updataLight = function(){
	 this.lightPositionParam.value = eyePosi;
	}
	


var worker = worker || {};//改变颜色等一系列函数的对象。

worker.removeCubes = function(){
	if(cubeMass[0]){
		worker.removeAllCubes(cubeMass);
		}
	}
	
worker.removeAllCubes = function(mass){
		if (mass[0])
		   {				 
		   cubeSelect.push(mass);
		   var massLength = mass.length;
		 	for (var n=massLength-1;n>=0;n--)
			    {
				 worker.removeAllCubes(mass[n]);
				 cubeSelect[cubeSelect.length-1].splice(n,1);
				}			
				cubeSelect.pop();
			}
		else 
		{
			mass.transform.parent = null;
			cubePack.removeObject(mass.transform);
			mass.parent = null;
			mass = null;
			
		}
	}

worker.create = function(stringData){
	worker._justCreate(stringData);
	}

worker._justCreate = function(stringData){
	var shiftN = 0;
	var n = 0;
	var createN = 0;
	while(n*13+shiftN<stringData.length){
		var label = stringData.substr(n*13+shiftN,1);
		if(label == "["){
			var newMass = new Array;
				newMass.transform = cubePack.createObject("Transform");
				newMass.transform.parent = cubeSelect[cubeSelect.length-1].transform;
				newMass.parent = cubeSelect[cubeSelect.length-1];
				newMass.localX = parseInt(stringData.substr(n*13+shiftN+1,2),36)-648;
				newMass.localY = parseInt(stringData.substr(n*13+shiftN+3,2),36)-648;
				newMass.localZ = parseInt(stringData.substr(n*13+shiftN+5,2),36)-648;
				newMass.x = newMass.localX + newMass.parent.x;
				newMass.y = newMass.localY + newMass.parent.y;
				newMass.z = newMass.localZ + newMass.parent.z;
				newMass.transform.translate(newMass.localX,newMass.localY,newMass.localZ);
			cubeSelect[cubeSelect.length-1].push(newMass);
			cubeSelect.push(newMass);
			shiftN += 8;
			worker._justCreate(stringData.substr(n*13+shiftN));
			break;
			}
		else if(label == "]"){
			cubeSelect.pop();
			shiftN += 1;
			if(!createN && n){
				//删除这个空的组
				var tempMass = cubeSelect[cubeSelect.length-1][cubeSelect[cubeSelect.length-1].length-1];
				cubePack.removeObject(tempMass.transform);
				tempMass.transform.parent = null;
				tempMass.parent = null;
				cubeSelect[cubeSelect.length-1].pop();
				}
			}
		else{
			var newCube = worker.createACubeByString(stringData.substr(n*13+shiftN,13));
			if(newCube){createN++;}
			n++;
			}
		}
	return newMass;
	}

worker.createACubeByString = function(stringData){
	var newCube = new creator.copyCube(	shape[0].cubeShape,
										parseInt(stringData.substr(1,2),16)/255,
										parseInt(stringData.substr(3,2),16)/255,
										parseInt(stringData.substr(5,2),16)/255,
										parseInt(stringData.substr(0,1),16)/10,
										parseInt(stringData.substr(7,2),36)-648,
										parseInt(stringData.substr(9,2),36)-648,
										parseInt(stringData.substr(11,2),36)-648,
										1);
			if(newCube.transform){
				cubeSelect[cubeSelect.length-1].push(newCube);
				return newCube;
				}
	}


worker.updataAllLight = function(){
	shape[0].updataLight();
	}

//背景对象
var backGround = backGround || {};


backGround.init = function(){
	backMaterial = o3djs.material.createMaterialFromFile(cubePack,
															 materialUrls[0],
															 backViewInfo.zOrderedDrawList);
	backMaterial.getParam("colorMult").value = [1, 1, 1, 1];
	backMaterial.drawList = backViewInfo.zOrderedDrawList;
	shape[5] = o3djs.primitives.createPlane(cubePack,
												backMaterial,
												1,
												1,
												1,
												1,
												[[1, 0, 0, 0],
												[0, 0, 1, 0],
												[0,-1, 0, 0],
												[0, 0, 0, 1]]);
	var repectTexture = backGround.createTexture([[1,1,1,1],[0.5,0.6,0.8,1]],10,700,"upToDown");
	//var repectTexture = backGround.createTexture([1,1,1,1],10,700);
	for(var n=0;n<100;n++){
		backImage[n] = new backGround.frame("chips0",[],[repectTexture],[],[]);
		backImage[n].moveTo(n*10,0);
		backImage[n].changeZ(-500);
		}
	}
	
backGround.createTexture = function(color,width,height,direction){
	
			var bgColorTexture = cubePack.createTexture2D(
														 width,
														 height,
														 o3djs.base.o3d.Texture.ARGB8,
														 1,
														 false);
			
			var linearPaint = cubePack.createObject('CanvasPaint');

			
			var bgImageCanvas = cubePack.createObject("Canvas");
			bgImageCanvas.setSize(width,height);
			
			if(color[0][0] != undefined){
				bgImageCanvas.clear([0,0,0,0]);
				var gradientShader = cubePack.createObject("CanvasLinearGradient");
				switch(direction){
					case "leftToRight":
						gradientShader.startPoint = [-1, 0];
						gradientShader.endPoint = [width-1, 0];
						break;
					case "rightToLeft":
						gradientShader.startPoint = [width-1, 0];
						gradientShader.endPoint = [-1, 0];
						break;
					case "downToUp":
						gradientShader.startPoint = [0, height-1];
						gradientShader.endPoint = [0, -1];
						break;
					case "upToDown":
						gradientShader.startPoint = [0, 0];
						gradientShader.endPoint = [0, height];
						break;
					default :
						gradientShader.startPoint = [0, 0];
						gradientShader.endPoint = [width, 0];
						break;
					}
					gradientShader.colors = color;
					gradientShader.positions = [];
					gradientShader.tileMode = cubeO3d.CanvasShader.REPEAT;
				linearPaint.shader = gradientShader;
				bgImageCanvas.drawRect(0,0,width,height,linearPaint);
				}
			else{
				bgImageCanvas.clear(color);
				}
			bgColorTexture.drawImage(bgImageCanvas,0,height-1,width,-height,
									   0,0,0,width,height
									   );	
			return bgColorTexture;
	}

	
	
backGround.frame = function(name,text,bgImage,bgColor,activation,z_index){
	this.name = name;
	this.x = 0;
	this.y = 0;
	this.z = z_index == undefined ? 0 : z_index;
	
	this.textContent = text[0];
	this.textCoordinateX = text[1] ? text[1] : 0;
	this.textCoordinateY = text[2] ? text[2] : 0;
	this.textTypeface = text[3] ? text[3] : "Microsoft YaHei";
	this.textSize = text[4] ? text[4] : 10;
	this.textColor = text[5] ? text[5] : [0,0,0,1];
	this.limitWidth = text[6] ? text[6] : 99999999;
	
	this.bgImageTexture = bgImage[0];
	this.bgImageTextureAlpha = bgImage[1] != undefined ? bgImage[1] : 1;
	this.bgImageWidth = bgImage[2];
	this.bgImageHeight = bgImage[3];
	
	this.bgColor = bgColor[0];
	this.bgWidth = bgColor[1];
	this.bgHeight = bgColor[2];
	this.bgDirection = bgColor[3];
	
	if(activation["activeDown"]){
		this.activeDown = activation["activeDown"];
		}
		else{
			this.activeDown = function(){};
			}
			
	if(activation["activeOver"]){
		this.activeOver = activation["activeOver"];
		}
		else{
			this.activeOver = function(){};
			}
			
	if(activation["activeUp"]){
		this.activeUp = activation["activeUp"];
		}
		else{
			this.activeUp = function(){};
			}
	if(activation["activeDrag"]){
		this.activeDrag = activation["activeDrag"];
		}
		else{
			this.activeDrag = function(){};
			}
	if(activation["activeLeave"]){
		this.activeLeave = activation["activeLeave"];
		}
		else{
			this.activeLeave = function(){};
			}
	
	if(activation["defultFunction"]){
		this.defultFunction = activation["defultFunction"];
		}
		else{
			this.defultFunction = function(){};
		}
			
	this.transform = cubePack.createObject("Transform");
	this.transform.parent = backImage.transform;
	this.scaleTransform = cubePack.createObject("Transform");
	this.scaleTransform.parent = this.transform;
	
	this.transform.translate(0,0,this.z);
	//----------------------------------------------------------------------
	if(this.bgImageTexture){
		this.bgImageMoveTransform = cubePack.createObject("Transform");
		this.bgImageMoveTransform.parent = this.scaleTransform;
		
		this.bgImageTransform = cubePack.createObject("Transform");
		this.bgImageTransform.parent = this.bgImageMoveTransform;
		
		this.bgImageSampler = cubePack.createObject('Sampler');
		this.bgImageSampler.addressModeU = cubeO3d.Sampler.CLAMP;
		this.bgImageSampler.addressModeV = cubeO3d.Sampler.CLAMP;
		
		this.bgImageParamSampler = this.bgImageTransform.createParam('texSampler0',
														'ParamSampler');
		this.bgImageParamSampler.value = this.bgImageSampler;
		this.bgImageParamColorMult = this.bgImageTransform.createParam('colorMult',
														'ParamFloat4');
		
		this.bgImageParamColorMult.set(1, 1, 1, this.bgImageTextureAlpha);
		
		this.bgImageSampler.texture = this.bgImageTexture;
		this.bgImageTransform.addShape(shape[5]);	
		
			if(this.bgImageWidth && this.bgImageHeight){
				this.width = this.bgImageWidth;
				this.height = this.bgImageHeight;
				}
			else{
				this.width = this.bgImageTexture.width;
				this.height = this.bgImageTexture.height;
				}
		this.bgImageTransform.translate(this.width/2,this.height/2,0);
		this.bgImageTransform.scale(this.width,-this.height,1);
		
		//this.bgImageMoveTransform.translate(this.bgImageCoordinateX,this.bgImageCoordinateX,0);
		}
		else if(this.bgColor  && this.bgColor[0] != undefined){
			this.width = this.bgWidth;
			this.height = this.bgHeight;
			
			this.bgImageMoveTransform = cubePack.createObject("Transform");
			this.bgImageMoveTransform.parent = this.scaleTransform;
			
			this.bgImageTransform = cubePack.createObject("Transform");
			this.bgImageTransform.parent = this.bgImageMoveTransform;
			
			this.bgColorTexture = cubePack.createTexture2D(
														 this.width,
														 this.height,
														 o3djs.base.o3d.Texture.ARGB8,
														 1,
														 false);
			
			var linearPaint = cubePack.createObject('CanvasPaint');

			
			this.bgImageCanvas = cubePack.createObject("Canvas");
			this.bgImageCanvas.setSize(this.width,this.height);
			
			if(this.bgColor[1][0] != undefined){
				this.bgImageCanvas.clear([0,0,0,0]);
				var gradientShader = cubePack.createObject("CanvasLinearGradient");
				switch(this.bgDirection){
					case "leftToRight":
						gradientShader.startPoint = [-1, 0];
						gradientShader.endPoint = [this.width-1, 0];
						break;
					case "rightToLeft":
						gradientShader.startPoint = [this.width-1, 0];
						gradientShader.endPoint = [-1, 0];
						break;
					case "downToUp":
						gradientShader.startPoint = [0, this.height-1];
						gradientShader.endPoint = [0, -1];
						break;
					case "upToDown":
						gradientShader.startPoint = [0, 0];
						gradientShader.endPoint = [0, this.height];
						break;
					default :
						gradientShader.startPoint = [0, 0];
						gradientShader.endPoint = [this.width, 0];
						break;
					}
					gradientShader.colors = this.bgColor;
					gradientShader.positions = [];
					gradientShader.tileMode = cubeO3d.CanvasShader.REPEAT;
				linearPaint.shader = gradientShader;
				this.bgImageCanvas.drawRect(0,0,this.width,this.height, linearPaint);
				}
			else{
				this.bgImageCanvas.clear(this.bgColor);
				}
			this.bgColorTexture.drawImage(this.bgImageCanvas,0,this.height-1,this.width,-this.height,
									   0,0,0,this.width,this.height
									   );
			this.bgImageSampler = cubePack.createObject('Sampler');
			this.bgImageSampler.addressModeU = cubeO3d.Sampler.CLAMP;
			this.bgImageSampler.addressModeV = cubeO3d.Sampler.CLAMP;
			
			this.bgImageParamSampler = this.bgImageTransform.createParam('texSampler0',
															'ParamSampler');
			this.bgImageParamSampler.value = this.bgImageSampler;
			this.bgImageParamColorMult = this.bgImageTransform.createParam('colorMult',
															'ParamFloat4');
			this.bgImageParamColorMult.set(1, 1, 1, 1);
				
			this.bgImageSampler.texture = this.bgColorTexture;
			this.bgImageTransform.addShape(shape[5]);	
			
			this.bgImageTransform.translate(this.width/2,this.height/2,0);
			this.bgImageTransform.scale(this.width,-this.height,1);
			//this.bgImageMoveTransform.translate(this.bgImageCoordinateX,this.bgImageCoordinateX,0);
			}
			else if(this.bgColor == undefined){
				this.width = this.bgWidth;
				this.height = this.bgHeight;
				}
	//========================================================================
	if(this.textContent){
		this.textMoveTransform = cubePack.createObject("Transform");
		this.textMoveTransform.parent = this.scaleTransform;
		
		this.textTransform = cubePack.createObject("Transform");
		this.textTransform.parent = this.textMoveTransform;
		
		
		this.textPaint = cubePack.createObject("CanvasPaint");
		this.textPaint.color = this.textColor;
		this.textPaint.textSize = this.textSize;
		this.textPaint.textTypeface = this.textTypeface;
		var fontBox = this.textPaint.measureText(this.textContent);
		this.textWidth = fontBox[2]-fontBox[0];
		this.textHeight = fontBox[3]-fontBox[1];
			if(this.textWidth>this.limitWidth){
				//按合适的宽度拆分字符串，保存到splitText（一个数组）
				var writeInRows = true;
				var splitText = dialog.splitTextBy(this.textPaint,this.textContent,this.limitWidth);
				fontBox = this.textPaint.measureText(splitText[0]);
				this.textWidth = this.limitWidth;
				this.textHeight = (fontBox[3]-fontBox[1]+3)*splitText.length;
				}
		
		if (this.textHeight%2 != 0){this.textHeight = this.textHeight +1;}
		if (this.textWidth %2 != 0){this.textWidth = this.textWidth +1;}
		
		this.textTexture = cubePack.createTexture2D(
													 this.textWidth,
													 this.textHeight,
													 o3djs.base.o3d.Texture.ARGB8,
													 1,
													 false);
		this.textCanvas = cubePack.createObject("Canvas");
		this.textCanvas.setSize(this.textWidth,this.textHeight);
		this.textCanvas.clear([1,1,1,0]);
		this.textTexture.drawImage(this.textCanvas,0,this.textHeight-1,this.textWidth,-this.textHeight,
								   0,0,0,this.textWidth,this.textHeight
								   );
		//根据暂存开关writeInRows来进入分支
			if(writeInRows){
				for(var nRows=0;nRows<splitText.length;nRows++){
					this.textCanvas.drawText(splitText[nRows],
										 -fontBox[0],
										 (fontBox[3]-fontBox[1])*(nRows+1)-fontBox[3]+nRows*3,
										 this.textPaint);
					}
				}
			else{
				this.textCanvas.drawText(this.textContent,
									 -fontBox[0],
									 this.textHeight-fontBox[3],
									 this.textPaint);
				}
		
		this.textTexture.drawImage(this.textCanvas,0,this.textHeight-1,this.textWidth,-this.textHeight,
								   0,0,0,this.textWidth,this.textHeight
								   );
		this.textSampler = cubePack.createObject('Sampler');
		this.textSampler.addressModeU = cubeO3d.Sampler.CLAMP;
		this.textSampler.addressModeV = cubeO3d.Sampler.CLAMP;
		
		this.textParamSampler = this.textTransform.createParam('texSampler0',
														'ParamSampler');
		this.textParamSampler.value = this.textSampler;
		this.textParamColorMult = this.textTransform.createParam('colorMult',
														'ParamFloat4');
		
		this.textParamColorMult.set(1, 1, 1, 1);
		
		this.textSampler.texture = this.textTexture;
		this.textTransform.addShape(shape[5]);	
		
		this.textTransform.translate(this.textWidth/2,this.textHeight/2,0.001);
		this.textTransform.scale(this.textWidth,-this.textHeight,1);
		
		if (!this.width){
			this.width = this.textWidth;
		}
		if (!this.height){
			this.height = this.textHeight;
 			}
		
		if (this.textCoordinateX  == "left"){
			this.textMoveTransform.translate(3,0,0);
			}else if (this.textCoordinateX  == "center"){
				this.textMoveTransform.translate(Math.round((this.width - this.textWidth - 3)/2),0,0);
				}else if(this.textCoordinateX  == "right"){
					this.textMoveTransform.translate(this.width - this.textWidth,0,0);
					}else {
						this.textMoveTransform.translate(this.textCoordinateX,0,0);
						}
		if (this.textCoordinateY  == "top"){
			this.textMoveTransform.translate(0,3,0);
			}else if (this.textCoordinateY  == "middle"){
				this.textMoveTransform.translate(0,Math.round((this.height - this.textHeight)/2),0);
				}else if(this.textCoordinateY  == "bottom"){
					this.textMoveTransform.translate(0,this.height - this.textHeight - 3,0);
					}else{
						this.textMoveTransform.translate(0,this.textCoordinateY,0);
						}
		}
	}

backGround.frame.prototype.moveTo = function(x,y){
	this.x = x;
	this.y = y;
	this.transform.identity();
	this.transform.translate(x,y,this.z);
	
	}
	
backGround.frame.prototype.changeZ = function(z){
	this.z = z;
	this.transform.identity();
	this.transform.translate(this.x,this.y,z);
	}
</script>

<style type="text/css">
<!--
#body{
	margin: 0px;
	padding: 0px;
}
#o3d{
	height: 340px;
	width: 640px;
	top: 50px;
	outline: none;
	position: absolute;
	background-image: url(ipic/egg.png);
	background-repeat: repeat;
}
#container {
	height: 740px;
	outline: none;
}
#backLine_bottom {
	background-image: url(../iPic/o3dElement_line_up.png);
	background-repeat: repeat-x;
	position: absolute;
	height: 20px;
	width: 100%;
	top: 720px;
}
#backLine_top {
	background-image: url(../iPic/o3dElement_line_top.png);
	background-repeat: repeat-x;
	position: absolute;
	height: 740px;
	width: 100%;
	top: 30px;
}
#body p#eizia{
	display: block;
	margin: 0px;
	padding: 0px;
	font-family: "微软雅黑", Verdana, Tahoma;
	font-size: 36px;
	position: absolute;
	width: 100%;
}
#useGuide {
	position: absolute;
	width: 100%;
	top: 780px;
	font-family: "微软雅黑", Verdana, Tahoma;
	font-size: 16px;
}
#useGuide span.title{
	font-weight: bold;
	color: #FB3613;	
}
#dataForm {
	position: absolute;
	top: 760px;	
}
#body #capture {
	position: absolute;
	top: 1000px;
}
#body #saveInfo {
	position: absolute;
	top: 900px;
}
-->
</style>
</head> 

<body id="body">
<p id="eizia">&nbsp;eizia</p>
<div id="o3d" >
</div>
<form id="dataForm">
<p>输入：<input name="createString" id="createString" type="text" size="117" /><br/>
</form>
</body>
</html>
